import axios from 'axios'

class HttpRequest {
  constructor() {
    this.baseUrl = process.env.VITE_APP_BASE_URL
    this.timeout = 5000
  }

  setInterceptor(instance) {
    instance.interceptors.request.use(config => {
      console.log('config===>', config.url, 'data===>', config.data, 'params===>', config.params)
      return config
    })
    instance.interceptors.response.use(
      response => {
        console.log('response===>' + response.config.url, response.data)
        return response.data
      },
      error => {
        return Promise.reject(error)
      }
    )
  }

  request(options) {
    const instance = axios.create({
      baseURL: this.baseUrl,
      timeout: options.timeout || this.timeout || 5000
    })
    this.setInterceptor(instance)
    return instance(options)
  }

  get(url, params = {}) {
    return this.request({
      method: 'get',
      url,
      params
    })
  }

  post(url, data = {}) {
    return this.request({
      method: 'post',
      url,
      data
    })
  }

  // 上传
  upload(url, data = {}) {
    return this.request({
      method: 'post',
      url,
      data,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  // 下载
  download(url, data = {}) {
    return this.request({
      method: 'post',
      url,
      data,
      responseType: 'blob'
    })
  }
}

export default new HttpRequest()
